<template>
  <view class="container">
    <view class="order-detail">
      <view v-if="userAddrDto" class="delivery-addr">
        <view class="user-info">
          <text class="item">
            {{ userAddrDto.receiver }}
          </text>
          <text class="item">
            {{ userAddrDto.mobile }}
          </text>
        </view>
        <view class="addr">
          {{ userAddrDto.province }}{{ userAddrDto.city }}{{ userAddrDto.area
          }}{{ userAddrDto.area }}{{ userAddrDto.addr }}
        </view>
      </view>

      <!-- 商品信息 -->
      <view v-if="orderItemDtos" class="prod-item">
        <block v-for="(item, index) in orderItemDtos" :key="index">
          <view class="item-cont" :data-prodid="item.prodId" @tap="toProdPage">
            <view class="prod-pic">
              <image :src="item.pic" />
            </view>
            <view class="prod-info">
              <view class="prodname">
                {{ item.prodName.split(" ")[0] }}
              </view>
              <view class="prod-info-cont">
                <text class="number"> 样品数量：{{ item.prodCount }} </text>
                <!-- <text class="info-item">
                  {{ item.skuName }}
                </text> -->
              </view>
              <!-- <view class="price-nums clearfix">
                <text class="prodprice">
                  <text class="symbol"> ￥ </text>
                  <text class="big-num">
                    {{ wxs.parsePrice(item.price)[0] }}
                  </text>
                  <text class="small-num">
                    .{{ wxs.parsePrice(item.price)[1] }}
                  </text>
                </text>
                <view class="btn-box" />
              </view> -->
            </view>
          </view>
        </block>
      </view>

      <!-- 检测结果展示 -->
      <view v-if="detectionResult" class="detection-result-section">
        <view class="detection-result-title">
          <text class="title-text">检测结果</text>
        </view>
        <view class="detection-result-content">
          <text class="result-label">检测报告链接：</text>
          <view class="result-link" @tap="copyDetectionResult">
            <text class="link-text">{{ detectionResult }}</text>
            <text class="copy-icon">📋</text>
          </view>
          <text class="copy-tip">点击复制链接</text>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="order-msg">
        <view class="msg-item">
          <view class="item">
            <text class="item-tit"> 订单编号： </text>
            <text class="item-txt">
              {{ orderNumber }}
            </text>
          </view>
          <view class="item">
            <text class="item-tit"> 下单时间： </text>
            <text class="item-txt">
              {{ createTime }}
            </text>
          </view>
          <view class="item">
            <text class="item-tit"> 样品名称： </text>
            <text class="item-txt">
              {{ sampleName }}
            </text>
          </view>
          <view class="item">
            <text class="item-tit"> 样品编号： </text>
            <text class="item-txt">
              {{ sampleNo }}
            </text>
          </view>
          <view class="item" v-for="orderItem in orderConfig">
            <text class="item-tit" v-if="orderItem.name">
              {{ orderItem.name }}：
            </text>
            <text
              class="item-txt"
              v-if="
                orderItem.infoFrom == 'in' && orderItem.choseType == 'input'
              "
            >
              {{ orderItem.value }}
            </text>

            <text
              class="item-txt"
              v-else-if="
                orderItem.infoFrom == 'in' &&
                (orderItem.choseType == 'checkbox' ||
                  orderItem.choseType == 'single')
              "
            >
              {{ getCheckboxValue(orderItem.value) }}
            </text>
            <text
              class="item-txt"
              v-else-if="
                orderItem.infoFrom == 'out' ||
                orderItem.infoFrom == 'etchingDepth'
              "
            >
              {{ orderItem.value }}
            </text>
            <text class="item-txt" v-else-if="orderItem.infoFrom == 'testTime' || orderItem.infoFrom == 'SEMTsetTime'">
              {{ orderItem.value }}分钟
            </text>
            <text
              class="item-txt"
              v-else-if="
                orderItem.infoFrom == 'joinTimes' ||
                orderItem.infoFrom == 'roiTimes'
              "
            >
              {{ orderItem.value }}次
            </text>
            <text
              class="item-txt"
              v-else-if="orderItem.infoFrom == 'needReturn'"
            >
              {{ orderItem.value ? "是" : "否" }}
            </text>
            <text
              class="item-txt"
              v-else-if="orderItem.infoFrom == 'needCloudVideo'"
            >
              {{
                orderItem.value == 0
                  ? "否"
                  : "是；" + "云视频时长：" + orderItem.value + "分钟"
              }}
            </text>
          </view>
        </view>
        <view class="msg-item">
          <view class="item">
            <text class="item-tit"> 支付方式： </text>
            <text class="item-txt"> 微信支付 </text>
          </view>
          <view class="item">
            <text class="item-tit"> 联系方式： </text>
            <text class="item-txt"> {{ contactPhone }} </text>
          </view>
          <view class="item">
            <text class="item-tit"> 额外文件： </text>
            <view
              class="item-file"
              v-for="(file, index) in extraFile.split(',')"
              :key="file"
            >
              <text class="file-name">文件{{ index + 1 }}</text>
              <text class="copy-btn" @tap="copyFileLink(file)"
                >复制文件地址</text
              >
            </view>
          </view>
          <!-- <view class="item">
            <text class="item-tit">
              配送方式：
            </text>
            <text class="item-txt">
              普通配送
            </text>
          </view> -->
          <view class="item">
            <text v-if="!!remarks" class="item-tit"> 订单备注： </text>
            <text class="item-txt remarks">
              {{ remarks }}
            </text>
          </view>
        </view>
      </view>

      <view class="order-msg">
        <view class="msg-item">
          <view class="item">
            <view class="item-tit"> 订单状态： </view>
            <view class="item-txt price">
              <text class="big-num">
                {{ getOrderStatusText(status) }}
              </text>
            </view>
          </view>
          <view class="item">
            <view class="item-tit"> 订单总额： </view>
            <view class="item-txt price">
              <text class="symbol"> ￥ </text>
              <text class="big-num">
                {{ wxs.parsePrice(actualTotal)[0] }}
              </text>
              <text class="small-num">
                .{{ wxs.parsePrice(actualTotal)[1] }}
              </text>
            </view>
          </view>
          <!-- <view class="item">
            <view class="item-tit">
              运费：
            </view>
            <view class="item-txt price">
              <text class="symbol">
                ￥
              </text>
              <text class="big-num">
                {{ wxs.parsePrice(transfee)[0] }}
              </text>
              <text class="small-num">
                .{{ wxs.parsePrice(transfee)[1] }}
              </text>
            </view>
          </view> -->
          <view class="item payment">
            <view class="item-txt price">
              实付款：
              <text class="symbol"> ￥ </text>
              <text class="big-num">
                {{ wxs.parsePrice(actualTotal)[0] }}
              </text>
              <text class="small-num">
                .{{ wxs.parsePrice(actualTotal)[1] }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部栏 -->
      <view v-if="status == 5 || status == 6" class="order-detail-footer">
        <text
          v-if="status == 5 || status == 6"
          class="dele-order"
          @tap="delOrderList"
        >
          删除订单
        </text>
      </view>
    </view>
  </view>
</template>

<script setup>
const wxs = number();

/**
 * 生命周期函数--监听页面加载
 */
onLoad((options) => {
  loadOrderDetail(options.orderNum);
});

/**
 * 跳转商品详情页
 * @param e
 */
const toProdPage = (e) => {
  const prodid = e.currentTarget.dataset.prodid;
  uni.navigateTo({
    url: "/pages/prod/prod?prodid=" + prodid,
  });
};

/**
 * 根据订单状态值获取对应的文本显示
 */
const getOrderStatusText = (status) => {
  const statusMap = {
    1: "待付款",
    2: "待检测",
    3: "待用户确认",
    4: "待评价",
    5: "成功",
    6: "失败",
    7: "检测中",
    8: "已取消",
    9: "待改价",
    10: "改价完成待支付",
  };

  return statusMap[status] || "已取消";
};

const remarks = ref("");
const orderItemDtos = ref([]);
const reduceAmount = ref("");
const transfee = ref("");
const status = ref(0);
const actualTotal = ref(0);
const userAddrDto = ref(null);
const orderNumber = ref("");
const createTime = ref("");
const total = ref(0); // 商品总额
const orderConfig = ref([]);
const sampleName = ref("");
const sampleNo = ref("");
const detectionResult = ref(""); // 检测结果链接
const contactPhone = ref(""); // 联系方式
const extraFile = ref(""); // 额外文件

/**
 * 加载订单数据
 */
const loadOrderDetail = (orderNum) => {
  uni.showLoading(); // 加载订单详情
  http
    .request({
      url: "/p/myOrder/orderDetail",
      method: "GET",
      data: {
        orderNumber: orderNum,
      },
    })
    .then(({ data }) => {
      orderNumber.value = orderNum;
      actualTotal.value = data.actualTotal;
      userAddrDto.value = data.userAddrDto;
      remarks.value = data.remarks;
      sampleName.value = data.sampleName;
      sampleNo.value = data.sampleNo;
      orderItemDtos.value = data.orderItemDtos;
      createTime.value = data.createTime;
      status.value = data.status;
      transfee.value = data.transfee;
      reduceAmount.value = data.reduceAmount;
      total.value = data.total;
      orderConfig.value = JSON.parse(data.orderConfigJson);
      detectionResult.value = data.detectionResult || ""; // 获取检测结果链接
      console.log(orderConfig.value, "orderConfig.value");
      contactPhone.value = data.contactPhone;
      extraFile.value = data.extraFile;
      uni.hideLoading();
    });
};

const getCheckboxValue = (value) => {
  let str = "";
  value.forEach((item) => {
    if (item.select) {
      str += item.name + " ";
    }
  });
  return str;
};

/**
 * 复制文件链接地址
 * @param {string} fileName 文件名
 */
const copyFileLink = (fileName) => {
  if (!fileName) return;

  // 构建完整的文件URL
  const baseUrl = import.meta.env.VITE_APP_RESOURCES_URL;
  const fileUrl = `${baseUrl}/${fileName}`;

  // 使用uni-app的复制功能
  uni.setClipboardData({
    data: fileUrl,
    success: () => {
      uni.showToast({
        title: "文件链接已复制",
        icon: "success",
        duration: 2000,
      });
    },
    fail: () => {
      uni.showToast({
        title: "复制失败，请重试",
        icon: "none",
        duration: 2000,
      });
    },
  });
};

/**
 * 删除已完成||已取消的订单
 */
const delOrderList = () => {
  uni.showModal({
    title: "",
    content: "确定要删除此订单吗？",
    confirmColor: "#0f3679",
    success(res) {
      if (res.confirm) {
        uni.showLoading();
        http
          .request({
            url: "/p/myOrder/" + orderNumber.value,
            method: "DELETE",
          })
          .then(() => {
            uni.hideLoading();
            uni.showToast({
              title: res || "删除成功",
              icon: "none",
            });
            setTimeout(() => {
              uni.redirectTo({
                url: "/pages/orderList/orderList",
              });
            }, 1000);
          });
      }
    },
  });
};

/**
 * 复制检测结果链接
 */
const copyDetectionResult = () => {
  if (!detectionResult.value) return;

  uni.setClipboardData({
    data: detectionResult.value,
    success: () => {
      uni.showToast({
        title: "链接已复制",
        icon: "success",
        duration: 2000,
      });
    },
    fail: () => {
      uni.showToast({
        title: "复制失败",
        icon: "none",
        duration: 2000,
      });
    },
  });
};
</script>

<style scoped lang="scss">
@import "./order-detail.scss";
</style>
